define(['angular', 'ng/ng.plugins','jquery-ui',
    'plugin/jquery-treetable/jquery.treetable'
], function (angular) {
    'use strict';

    /**
     * Created by three on 14-7-22.
     */
    angular.module('app.plugins')
        .directive('dvTreeTable', ['$debounce','$compile', function ($debounce,$compile) {
            return {
                restrict: 'A',
                require: '?ngModel',
                scope: {
                    config: '&',
                    table: '=',
                    collapse: '=collapseAll'
                },
                link: function (scope, element, attrs, ngModel) {

                    if (!ngModel) return;

                    if (!attrs.id) { // 自动生成id
                        attrs.id = Math.uuid();
                        element.attr('id', attrs.id);
                    }

                    var table_config = scope.config();

                    // 构造table节点
                    if(table_config.title) element.append('<caption>'+table_config.title+'</caption>');

                    if(table_config.rootNodeUpId==null) {
                        table_config.rootNodeUpId = 0;
                    }

                    var thead_tr = jQuery('<tr data-tt-id="'+table_config.rootNodeUpId+'"></tr>');
                    element.append(jQuery('<thead></thead>').append(thead_tr));
                    for(var i=0; i<table_config.aoColumns.length; i++) {
                        var col = table_config.aoColumns[i];
                        thead_tr.append(jQuery('<th class="moveable"></th>').append(col['sTitle']))
                    }

                    // 加入 tbody数据
                    var tbody = jQuery('<tbody></tbody>');
                    element.append(tbody);
                    element.treetable({
                        expandable: true
                    });

                    // 告诉angularJS内部模型改变后，怎么更新界面
                    ngModel.$render = function () {
                        if(ngModel.$viewValue && ngModel.$viewValue.$resolved) {
                            show_in_table(ngModel.$viewValue);
                        }
                    };

                    // 显示treetable实现
                    var show_in_table = function (data) {
                        var records = data;
                        element.treetable('destroy');
                        tbody.html('');
                        // 构造树形结构显示
                        scope.funcs = {};
                        var roots = [];
                        for(var i=0; i<records.length; i++) {
                            var row = records[i];
                            row['child'] = [];
                            scope.funcs['f'+row['id']] = row;
                        }
                        for(var i=0; i<records.length; i++) {
                            var row = records[i];
                            var p = scope.funcs['f'+row['upId']];
                            if(p) {
                                p.child.push(row)
                            } else {
                                roots.push(row);
                            }
                        }
                        // 递归显示菜单节点
                        (function showNode(nodes) {
                            for(var i=0; i<nodes.length; i++) {
                                var row = nodes[i];
                                var tbody_tr = jQuery('<tr></tr>');
                                tbody.append(tbody_tr);

                                tbody_tr.attr('data-tt-id', row['id']);

                                row['upId'] && tbody_tr.attr('data-tt-parent-id', row['upId']);

                                for(var j=0; j<table_config.aoColumns.length; j++) {
                                    var tbody_tr_td = jQuery('<td></td>');

                                    tbody_tr.append(tbody_tr_td);
                                    var prop = table_config.aoColumns[j]['mDataProp'];
                                    var render = table_config.aoColumns[j]['render'];
                                    var value = (render && typeof(render)=='function') ?render(row[prop],'jquery',row, tbody_tr_td) :row[prop];

                                    if(j==0) {
                                        value='<span class="moveable" style="padding: 0px; margin: 0px;">'+value+'</span>';
                                    }

                                    tbody_tr_td.append(value);
                                }
                                showNode(row.child)
                            }
                        })(roots);

                        var dynamicOdd = function (el) {
                            el.find('>tbody >tr:visible').each(function (index) {
                                var _this = jQuery(this);
                                _this.removeClass('odd').removeClass('even');
                                if(index%2==0) {
                                    _this.addClass('odd');
                                    _this.attr('style-type','odd');
                                } else {
                                    _this.addClass('even');
                                    _this.attr('style-type','even');
                                }
                            })
                        };


                        // treetable初始化
                        element.treetable({
                            expandable: true,
                            onInitialized: function () {
                                dynamicOdd(element);
                            },
                            onNodeCollapse: function () {
                                dynamicOdd(element);
                            },
                            onNodeExpand: function () {
                                dynamicOdd(element);
                            },
                            onNodeInitialized: function () {

                            }
                        });

                        // 编译绑定
                        $compile(element.children())(scope.$parent);

                        table_config.drawCallback && typeof(table_config.drawCallback)=='function' && table_config.drawCallback();

                        // Highlight selected row
                        jQuery("#"+attrs.id+" tbody").on("mousedown", "tr", function() {
                            jQuery(".isSelected").not(this).removeClass("isSelected");
                            jQuery(this).toggleClass("isSelected");
                        });

                        // hover
                        jQuery("#"+attrs.id+" tbody").on("mouseover", "tr", function() {
                            var _this = jQuery(this);
                            _this.removeClass(_this.attr('style-type'));
                        }).on("mouseout", "tr", function() {
                            var _this = jQuery(this);
                            _this.addClass(_this.attr('style-type'));
                        });

                        // Drag & Drop Example Code
                        jQuery("#"+attrs.id+" .moveable").draggable({
                            helper: "clone",
                            opacity: .75,
                            refreshPositions: true, // Performance?
                            revert: "invalid",
                            revertDuration: 300,
                            scroll: true
                        });

                        //  支持移动节点
                        if(table_config.move && table_config.move==true) {
                            jQuery("#" + attrs.id + " .moveable").each(function () {
                                jQuery(this).parents("#" + attrs.id + " tr").droppable({
                                    accept: ".moveable",
                                    drop: function (e, ui) {
                                        var droppedEl = ui.draggable.parents("tr"); // 移动的节点
                                        if(droppedEl.data("ttId") == table_config.rootNodeUpId) {
                                            return;
                                        }
                                        var confirm = true;
                                        if(table_config.moveCallback && typeof(table_config.moveCallback)=='function') {
                                            confirm = table_config.moveCallback(droppedEl.data("ttId"), jQuery(this).data("ttId"));
                                        }

                                        if(confirm==true) {
                                            jQuery("#" + attrs.id).treetable("move", droppedEl.data("ttId"), jQuery(this).data("ttId"));
                                        }
                                    },
                                    hoverClass: "accept",
                                    over: function (e, ui) {
                                        var droppedEl = ui.draggable.parents("tr");
                                        if (this != droppedEl[0] && !jQuery(this).is(".expanded")) {
                                            jQuery("#" + attrs.id).treetable("expandNode", jQuery(this).data("ttId"));
                                        }
                                    }
                                });
                            });
                        }

                        scope.$watch('collapse', function (collapse) {
                            if(collapse==true) {
                                element.treetable('collapseAll')
                            } else if(collapse==false) {
                                element.treetable('expandAll')
                            }
                        })
                    };
//
//                    jQuery("form#reveal").submit(function() {
//                        var nodeId = jQuery("#revealNodeId").val();
//
//                        try {
//                            jQuery("#"+attrs.id).treetable("reveal", nodeId);
//                        }
//                        catch(error) {
//                            alert(error.message);
//                        }
//
//                        return false;
//                    });
//
//                    $debounce(pagefunction, 200);
                }
            };
        }])
    ;

});